package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.vo.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    MarketBrandMapper marketBrandMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    SecurityManager securityManager;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    MarketIssueMapper marketIssueMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    @Autowired
    MarketCollectMapper marketCollectMapper;

    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;

    @Autowired
    MarketFootprintMapper marketFootprintMapper;

    @Override
    public WxGoodsListVo list(String keyword, final Integer brandId, final Integer categoryId, Integer page, Integer limit, String sort, String order) {

        if (!StringUtils.isEmpty(keyword)) {
            MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
            marketSearchHistory.setKeyword(keyword);
            marketSearchHistory.setUserId(userId());
            marketSearchHistory.setFrom("1");
            marketSearchHistory.setAddTime(LocalDateTime.now());
            marketSearchHistory.setUpdateTime(LocalDateTime.now());
            marketSearchHistory.setDeleted(true);
            marketSearchHistoryMapper.insert(marketSearchHistory);
        }

        // 只有brandId
        if (brandId != null && brandId != 0 && (keyword == null || "".equals(keyword) && (categoryId == null || "".equals(categoryId)))) {
            MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
            if (brandId != null && brandId != 0) {
                criteria.andBrandIdEqualTo(brandId);
            }
            PageHelper.startPage(page, limit);
            List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExample(marketGoodsExample);
            Map<Integer, String> map = new HashMap<>();
            for (final MarketGoods marketGoods : marketGoodsList) {
                Integer goodsCategoryId = marketGoods.getCategoryId();
                map.put(goodsCategoryId, "goodsCategoryId");
            }
            List<MarketCategory> categoryList = new ArrayList<>();
            Set<Integer> set = map.keySet();
            for (final Integer id : set) {
                MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(id);
                categoryList.add(marketCategory);
            }
            if (sort != null && !"".equals(sort) && order != null && !"".equals(order)) {
                marketGoodsExample.setOrderByClause(sort + " " + order);
            }
            WxGoodsListVo wxGoodsListVo = new WxGoodsListVo(categoryList, marketGoodsList);
            return wxGoodsListVo;
        }

        // keyword && categoryId
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteriaGoods = marketGoodsExample.createCriteria();
        if (keyword != null && !"".equals(keyword)) {
            criteriaGoods.andNameLike("%" + keyword + "%");
        }
        if (categoryId != null && categoryId != 0) {
            criteriaGoods.andCategoryIdEqualTo(categoryId);
        }
        List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExample(marketGoodsExample);
        Map<Integer, String> map = new HashMap<>();
        for (final MarketGoods marketGoods : marketGoodsList) {
            Integer goodsCategoryId = marketGoods.getCategoryId();
            map.put(goodsCategoryId, "goodsCategoryId");
        }
        List<MarketCategory> categoryList = new ArrayList<>();
        Set<Integer> set = map.keySet();
        for (final Integer id : set) {
            MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(id);
            categoryList.add(marketCategory);
        }
        if (sort != null && !"".equals(sort) && order != null && !"".equals(order)) {
            marketGoodsExample.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page, limit);
        List<MarketGoods> marketGoodsList2 = marketGoodsMapper.selectByExample(marketGoodsExample);

        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo(categoryList, marketGoodsList2);
        return wxGoodsListVo;

        // if (brandId != null) {
        //     MarketBrandExample marketBrandExample = new MarketBrandExample();
        //     List<MarketBrand> marketBrandList = marketBrandMapper.selectByExample(marketBrandExample);
        //     wxGoodsListVo.setMarketBrandList(marketBrandList);
        // }
        //
        // if (categoryId != null) {
        //     MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        //     List<MarketCategory> marketCategoryList = marketCategoryMapper.selectByExample(marketCategoryExample);
        //     wxGoodsListVo.setMarketCategoryList(marketCategoryList);
        // }
        //
        // MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        // MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        // if (brandId != null) {
        //     criteria.andBrandIdEqualTo(brandId);
        // }
        // if (categoryId != null) {
        //     criteria.andCategoryIdEqualTo(categoryId);
        // }
        // if (keyword != null && !"".equals(keyword)) {
        //     // criteria.andKeywordsLike("%" + keyword + "%");
        //     criteria.andNameLike("%" + keyword + "%");
        // }
        //
        // marketGoodsExample.setOrderByClause(sort + " " + order);
        //
        // PageHelper.startPage(limit, page);
        //
        // List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExampleSelective(marketGoodsExample);
        // wxGoodsListVo.setMarketGoodsList(marketGoodsList);
        // return wxGoodsListVo;
    }

    @Override
    public WxGoodsCategoryVo category(final Integer id) {

        String level = null;
        MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(id);
        level = marketCategory.getLevel();

        if ("L1".equals(level)) {
            MarketCategory parentCategory = marketCategoryMapper.selectByPrimaryKey(id);
            MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
            MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
            if (id != null) {
                criteria.andPidEqualTo(id);
            }
            List<MarketCategory> brotherCategory = marketCategoryMapper.selectByExample(marketCategoryExample);
            MarketCategory currentCategory = null;
            if (brotherCategory != null) {
                currentCategory = brotherCategory.get(0);
            }
            WxGoodsCategoryVo wxGoodsCategoryVo = new WxGoodsCategoryVo(brotherCategory, currentCategory, parentCategory);
            return wxGoodsCategoryVo;
        }

        if ("L2".equals(level)) {
            MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
            MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
            MarketCategory currentCategory = marketCategoryMapper.selectByPrimaryKey(id);
            Integer pid = currentCategory.getPid();
            MarketCategory parentCategory = marketCategoryMapper.selectByPrimaryKey(pid);
            if (pid != null) {
                criteria.andPidEqualTo(pid);
            }
            List<MarketCategory> brotherCategory = marketCategoryMapper.selectByExample(marketCategoryExample);
            WxGoodsCategoryVo wxGoodsCategoryVo = new WxGoodsCategoryVo(brotherCategory, currentCategory, parentCategory);
            return wxGoodsCategoryVo;
        }

        return null;
    }

    @Override
    public Long count() {
        long countAllGoods = marketGoodsMapper.countAll();
        return countAllGoods;
    }

    @Override
    public WxGoodsDetailVo detail(final Integer id, Integer userId2) {

        // footprint数据库写入
        MarketFootprintExample marketFootprintExample = new MarketFootprintExample();
        MarketFootprintExample.Criteria criteria = marketFootprintExample.createCriteria();
        if (id != null) {
            criteria.andGoodsIdEqualTo(id);
        }
        if (userId2 != null) {
            criteria.andUserIdEqualTo(userId2);
        }
        MarketFootprint footprint = marketFootprintMapper.selectOneByExample(marketFootprintExample);
        // 物理删除footprint浏览相同商品足迹
        if (footprint != null) {
            // MarketFootprintExample footprintExample = new MarketFootprintExample();
            // MarketFootprintExample.Criteria footprintExampleCriteria = footprintExample.createCriteria();
            // if (id != null) {
            //     footprintExampleCriteria.andGoodsIdEqualTo(id);
            // }
            // Integer deleteCount = marketFootprintMapper.deleteByExample(footprintExample);
            footprint.setUpdateTime(LocalDateTime.now());
            Integer updateCount = marketFootprintMapper.updateByPrimaryKey(footprint);
        } else {
            MarketFootprint marketFootprint = new MarketFootprint();
            marketFootprint.setUserId(userId2);
            marketFootprint.setGoodsId(id);
            marketFootprint.setAddTime(LocalDateTime.now());
            marketFootprint.setUpdateTime(LocalDateTime.now());
            marketFootprint.setDeleted(false);
            Integer insertCount = marketFootprintMapper.insert(marketFootprint);
        }

        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteriaAttribute = marketGoodsAttributeExample.createCriteria();
        criteriaAttribute.andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attribute = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);

        MarketGoods marketGood = marketGoodsMapper.selectByPrimaryKey(id);
        Integer brandId = marketGood.getBrandId();

        MarketBrand brand = marketBrandMapper.selectByPrimaryKeySelective(brandId);

        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria criteriaComment = marketCommentExample.createCriteria();
        criteriaComment.andValueIdEqualTo(id);
        List<MarketComment> marketCommentList = marketCommentMapper.selectByExample(marketCommentExample);
        Integer count = marketCommentList.size();
        List<WxMarketCommentVo2> wxMarketCommentVo2List = new ArrayList<>();
        for (final MarketComment marketComment : marketCommentList) {
            LocalDateTime addTime = marketComment.getAddTime();
            String adminContent = marketComment.getAdminContent();
            Integer userId = marketComment.getUserId();
            MarketUser user = marketUserMapper.selectByPrimaryKey(userId);
            if (user==null)continue;
            String avatar = user.getAvatar();
            String nickname = user.getNickname();
            String content = marketComment.getContent();
            Integer commentId = marketComment.getId();
            String[] picUrls = marketComment.getPicUrls();
            List<String> picList = new ArrayList<>();
            for (final String picUrl : picUrls) {
                picList.add(picUrl);
            }
            WxMarketCommentVo2 wxMarketCommentVo2 = new WxMarketCommentVo2(addTime, adminContent, avatar, content, commentId, nickname, picList);
            wxMarketCommentVo2List.add(wxMarketCommentVo2);
        }
        WxMarketCommentVo1 comment = new WxMarketCommentVo1(count, wxMarketCommentVo2List);

        MarketIssueExample marketIssueExample = new MarketIssueExample();
        List<MarketIssue> issue = marketIssueMapper.selectByExample(marketIssueExample);

        // MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        // MarketCommentExample.Criteria criteriaProduct = marketCommentExample.createCriteria();
        // if (id != null) {
        //     criteriaProduct.and(id);
        // }
        // List<MarketGoodsProduct> productList = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);

        List<MarketGoodsProduct> productList = marketGoodsProductMapper.selectByGoodsId(id);

        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria criteriaSpecification = marketGoodsSpecificationExample.createCriteria();
        if (id != null) {
            criteriaSpecification.andGoodsIdEqualTo(id);
        }
        List<MarketGoodsSpecification> marketGoodsSpecificationList = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        List<WxGoodsSpecificationVo> wxGoodsSpecificationVoList = new ArrayList<>();
        Map<String, Integer> mapName = new HashMap<>();
        for (final MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecificationList) {
            String specification = marketGoodsSpecification.getSpecification();
            mapName.put(specification, 0);
        }
        Set<String> nameSet = mapName.keySet();
        for (final String name : nameSet) {
            List<MarketGoodsSpecification> marketGoodsSpecificationList2 = new ArrayList<>();
            for (final MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecificationList) {
                if (name.equals(marketGoodsSpecification.getSpecification())) {
                    marketGoodsSpecificationList2.add(marketGoodsSpecification);
                }
            }
            WxGoodsSpecificationVo wxGoodsSpecificationVo = new WxGoodsSpecificationVo(name, marketGoodsSpecificationList2);
            wxGoodsSpecificationVoList.add(wxGoodsSpecificationVo);
        }

        String shareImage = marketGood.getShareUrl();

        MarketCollectExample marketCollectExample = new MarketCollectExample();
        MarketCollectExample.Criteria criteriaCollect = marketCollectExample.createCriteria();
        if (id != null) {
            criteriaCollect.andValueIdEqualTo(id);
        }
        List<MarketCollect> marketCollectList = marketCollectMapper.selectByExample(marketCollectExample);
        Integer userHasCollect = marketCollectList.size();

        boolean share = true;

        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo(attribute, brand, comment, marketGood, issue, productList, share, shareImage, wxGoodsSpecificationVoList, userHasCollect);
        return wxGoodsDetailVo;
    }

    @Override
    public List<MarketGoods> related(final Integer id) {
        MarketGoods marketGood = marketGoodsMapper.selectByPrimaryKey(id);
        Integer categoryId = marketGood.getCategoryId();
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        if (categoryId != null) {
            criteria.andCategoryIdEqualTo(categoryId);
        }

        PageHelper.startPage(1, 6);

        List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExample(marketGoodsExample);
        return marketGoodsList;
    }

    private Integer userId() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria userExampleCriteria = marketUserExample.createCriteria();
        userExampleCriteria.andUsernameEqualTo(user.getUsername());
        MarketUser marketUser = marketUserMapper.selectByExample(marketUserExample).get(0);
        Integer userId = marketUser.getId();
        return userId;
    }
}
